package com.aliengen.thingple.thingple.fillingstation;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.aliengen.thingple.beep.DevBeep;
import com.aliengen.thingple.thingple.AbstractThingpleActivity;
import com.aliengen.thingple.thingple.R;
import com.aliengen.thingple.thingple.handler.CMCHandler;
import com.aliengen.thingple.thingple.tag.CylinderTag;

public class SearchActivity extends AbstractThingpleActivity {

    protected CylinderTag cylinder;
    protected ImageView imageView;

    protected int powerLoopArray[] = {28, 26, 24, 22, 20, 18};

    private final SearchRadarThread thread = new SearchRadarThread();
    Boolean threadStop = false;
    Boolean found = false;
    Boolean tagSelected = false;

    int index = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        setOperatorName();

        this.cylinder = (CylinderTag) getIntent().getExtras().get("cylinder_tag");

        setText(R.id.cylinderReference, R.string.cylinder_reference, this.cylinder.getReference());
        imageView = (ImageView) findViewById(R.id.imageView);

        setRadarLevel(0);

        threadStop = false;
        thread.start();

        mApplication.getHandler().setOnEventListener(new CMCHandler.OnEventListener() {
            @Override
            public void onPressDown() {
            }

            @Override
            public void onPressUp() {
            }

            @Override
            public void onReceiveData() {
            }

            @Override
            public void onRead(String data) {
                Log.i("SearchActivity", "onRead");
                synchronized (SearchActivity.this) {
                    Log.i("SearchActivity", "interrupt");
                    thread.interrupt();
                }
                found = true;

            }

            @Override
            public void onReadFailed() {
                Log.i("SearchActivity", "onReadFailed");
                synchronized (SearchActivity.this) {
                    Log.i("SearchActivity", "interrupt");
                    thread.interrupt();
                }
            }

            @Override
            public void onWrite() {
            }

            @Override
            public void onWriteFailed() {
            }

            @Override
            public void onTagSelected() {
                tagSelected = true;
            }

            @Override
            public void onTagSelectFailed() {
                synchronized (SearchActivity.this) {
                    Log.i("SearchActivity", "interrupt: TagSelectFailed");
                    thread.interrupt();
                }
                showToast("Select function not working! Try to update the firmware!");
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        threadStop = true;

        synchronized (SearchActivity.this) {
            thread.interrupt();
        }
    }

    public void setRadarLevel(int level)
    {
        Log.i("SearchActivity", "setRadarLevel(" + level + ")");
        switch(level)
        {
            case 0:
                imageView.setImageResource(R.drawable.radar_0);
                break;
            case 1:
                imageView.setImageResource(R.drawable.radar_1);
                break;
            case 2:
                imageView.setImageResource(R.drawable.radar_2);
                break;
            case 3:
                imageView.setImageResource(R.drawable.radar_3);
                break;
            case 4:
                imageView.setImageResource(R.drawable.radar_4);
                break;
            case 5:
                imageView.setImageResource(R.drawable.radar_5);
                break;
            case 6:
                imageView.setImageResource(R.drawable.radar_6);
                break;
        }
    }

    public void onClickBack(View view)
    {
        this.finish();
    }

    class SearchRadarThread extends Thread {
        @Override
        public void run() {
            mApplication.mService.device.select(cylinder.getEpc(), 2000);

            while(!threadStop && !tagSelected)
            {
                synchronized (this) {
                    try {
                        this.sleep(300);
                    } catch (InterruptedException e) {
                        //e.printStackTrace();
                    }
                }
            }

            while(!threadStop) {
                found = false;
                /* Power loop. */
                for (index = powerLoopArray.length-1; index >= 0; index--) {
                    // Set power
                    mApplication.mService.device.setPower(powerLoopArray[index]);

                    mApplication.mService.device.read(200);

                    synchronized (this) {
                        try {
                            this.sleep(1000);
                        } catch (InterruptedException e) {
                            //e.printStackTrace();
                        }
                    }

                    if (found) {
                        Log.i("SearchRadarThread", "Found at " + index + "!");
                        // Beep
                        DevBeep.PlayOK();

                        // Set image
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                setRadarLevel(index + 1);
                            }
                        });

                        try {
                            this.sleep(10L);
                        } catch (InterruptedException e) {
                            //e.printStackTrace();
                        }
                        break;
                    }
                    Log.i("SearchRadarThread", "Not found at power " + powerLoopArray[index]);
                }

                if (!found) {
                    runOnUiThread(new Runnable() {
                                      @Override
                                      public void run() {
                                          setRadarLevel(0);
                                      }});
                }
            }
            mApplication.mService.device.unselect();
        }
    }
}
